<?php
/**
 * Goods
 * Created by Veyron
 * motto:现在的拼搏 为了更好的明天
 * day:  2020/1/21
 * Time: 17:14
 */

namespace app\common\business;
use app\common\business\Category as CategoryBis;
use app\common\business\GoodsSku as GoodsSkuBis;
use app\common\lib\Arr;
use app\common\lib\Show;
use app\common\model\mysql\Goods as GoodsModel;
use app\common\model\mysql\GoodsSku as GoodsSkuModel;
use think\Exception;
use think\facade\Cache;

class Goods extends BusBase
{
    public $model = null;
    public function __construct()
    {
        $this->model = new GoodsModel();
    }

    /**
     * 新增商品逻辑
     * @return array|bool|int|mixed
     */
    public function insertData($data){
        //开启一个事物
        $this->model->startTrans();
        try {
            $goodId = $this->add($data);

            //执行数据插入到 sku 表中
            //如果是统一规格
            if ($data['goods_specs_type'] == 1) {

                $goodsSkuData = [
                    'goods_id' => $goodId,
                    'specs_value_ids'   => 0,
                    'price'             => $data['price'],
                    'cost_price'        => $data['cost_price'],
                    'stock'             => $data['stock'],
                ];

                $goodsSkuBisObj = new GoodsSkuModel();
                $res = $goodsSkuBisObj->save($goodsSkuData);

                if(!$res){
                    throw new Exception('sku表新增失败');
                }
                //提交事务
                $this->model->commit();
                return true;
            } elseif ($data['goods_specs_type'] == 2) { //多规格是电商核心
                $goodsSkuBisObj = new GoodsSkuBis();
                $data['goods_id'] = $goodId;
                $res = $goodsSkuBisObj->saveAll($data);
                //如果库存不为空
//                $res = '' ; //模拟数据库操作失败
                if (!empty($res)) {
                    //总库存
                    $stock = array_sum(array_column($res, 'stock'));
                    $goodsUpdateData = [
                        'price' => $res[0]['price'],
                        'cost_price' => $res[0]['cost_price'],
                        'stock' => $stock,
                        'sku_id' => $res[0]['id']
                    ];
                    //执行完毕之后更新主表数据
                    $goodsRes = $this->model->updateById($goodId, $goodsUpdateData);
                    if (!$goodsRes) {
                        throw new Exception('insetData:Goods 主表更新失败');
                    }
                } else {
                    throw new Exception('sku表新增失败');
                }
            }
            //提交事务
            $this->model->commit();
            return true;
        }catch (Exception $e){
            //记录日志
            //事务回滚
            $this->model->rollback();
            return false;
        }
        return true;
    }

    /**
     * 商品列表
     */
    public function getLists($data,$num = 10){
        $likeKeys = [];
        if(!empty($data)){
            $likeKeys = array_keys($data);
        }
        try {
            $list = $this->model->getLists($likeKeys,$data,$num );
            $result = $list->toArray();
        }catch (\Exception $e){
           $result = Arr::getPaginateDefaultData($num);
        }
        return $result;
    }

    /**
     * 首页大图
     */
    public function getRotationChart(){
        $data = [
            'is_index_recommend'  => 1
        ];
        $field = "sku_id as id,title,big_image as image";
        try {
            $result = $this->model->getNormalGoodByCondittion($data,$field);
        }catch (\Exception $e){
            return [];
        }
        return $result->toArray();
    }

    public function categoryGoodsRecommend($categoryIds){
        if(!$categoryIds){
            return [];
        }

        $result = [];
        //获取分类栏目
        $categoryBisObj = new CategoryBis();
        //获取pid
        $categoryPids = $categoryBisObj->getNormalCategoryInPidsByIds($categoryIds, 'pid,id');

        if(!$categoryPids){
            return Show::error('分类不存在');
        }
        //pid为0 的获取自身id
        $wherePid = [];
        foreach ($categoryPids as $pid){
            if($pid['pid'] == 0){
                $wherePid[] = $pid['id'];
            }else{
                $wherePid[] = $pid['pid'];
            }
        }
        $categorys = $categoryBisObj->getNormalCategoryInPidsByIds($wherePid, 'id as category_id, name, icon');
        //获取子栏目
        $lists =  $categoryBisObj->getNormalCategoryInPidsByIds(array_column($categorys,'category_id'), 'name, id as category_id, pid','pid');
//        dump($lists);die;
        if($categorys){
            foreach ($categorys as $k => $category ){
                $result[$k]['categorys'] = [
                    'category_id'   => $category['category_id'],
                    'name'          => $category['name'],
                    'icon'          => $category['icon'],
                ];
                if(!empty($lists)){
                    foreach ($lists as $list){
                        if($result[$k]['categorys']['category_id'] == $list['pid']){
                            $result[$k]['categorys']['list'][] = $list;
                        }
                    }
                }

            }
        }

        //获取分类对应的商品
        foreach ($categoryIds as $k => $categoryId ){
            $result[$k]['goods'] = $this->getNormalGoodsFindInSetCategory($categoryId);
        }
        return $result;
    }

    /**
     * 使用 find_in_set 获取商品信息
     * @param $categoryId
     * @return array
     */
    public function getNormalGoodsFindInSetCategory($categoryId){
        $field = "sku_id as id, title, recommend_image as image, price";
        try {
            $result = $this->model->getNormalGoodsFindInSetCategory($categoryId,$field);
        }catch (\Exception $e){
            return [];
        }
        return $result->toArray();
    }

    /**
     * 使用 find_in_set 获取商品信息——带分页
     * @param $where
     * @param int $num
     * @return array
     */
    public function getNormalLists($data, $order, $num = 5 ){
        $field = "sku_id as id, title, recommend_image as image, price";
        try {
            $list = $this->model->getNormalLists($data, $order, $num, $field);
            $res  = $list->toArray();

            $result = [
                'total_page_num'    => isset($res['last_page']) ? $res['last_page'] : 0,
                'count'             => isset($res['total']) ? $res['total'] : 0,
                'page'              => isset($res['current_page']) ? $res['current_page'] : 0,
                'page_size'         => $num,
                'list'              => isset($res['data']) ? $res['data'] : [],
            ];
        }catch (\Exception $e){
            return [];
        }
        return $result;
    }

    public function getGoodsDetailBySkuId($skuId){
        //sku表 => goods_id goods表 => info sku => sku数据
        $goodsSkuBisObj = new GoodsSkuBis();
        //join 一般业务量大尽量少使用  join , 可进行两次 sql 查询
        $goodsSku = $goodsSkuBisObj->getNormalSkuAndGoods($skuId);
        if(!$goodsSku){
            return [];
        }
        $goods = $goodsSku['goods'];


        if($goods['goods_specs_type'] == 1){ //统一规格
            $sku = [];
        }else{ //多规格
            $skus = $goodsSkuBisObj->getSkusByGoodId($goods['id']);
            if(!$skus){
                return [];
            }
            $flagValue = '';
            foreach ($skus as $sku){
                if($sku['id'] == $skuId){
                    $flagValue = $sku['specs_value_ids'];
                }
            }

//          $gids = [];
//          foreach ($skus as $sku){
//                $gids[$sku['specs_value_ids']] = $sku['id'];
//          }
            //上面方法可化简为
            $gids = array_column($skus,'id','specs_value_ids');

            $sku = (new SpecsValue())->dealGoodsSkus($gids, $flagValue);
        }

        $result = [
            'title'          => $goods['title'],
            'price'          => $goodsSku['price'],
            'cost_price'     => $goodsSku['cost_price'],
            'sales_count'    => $goods['sales_count'],
            'stock'          => $goodsSku['stock'],
            'gids'           => $gids,
            'image'          => $goods['carousel_image'],
            'sku'            => $sku,
            'detail'         => [
                'd1'   => [
                    '商品编码'  => $goodsSku['id'],
                    '上架时间'  => $goods['create_time'],
                ],
                'd2'   =>  preg_replace('/(<img src=\")(.*?)\/upload\/image/', '$1'.request()->domain().'$2', $goods['description']),
            ]
        ];

        //记录数据到redis 作为商品PV
        Cache::inc('mall_pv_'.$goods['id']);

        return $result;
    }
    /**
     * 更新sku库存
     * @param $data
     * @return array|bool
     */
    public function updateStock($data){
        $ids = array_keys($data);

        try {
            $goods = $this->model->getNormalInIds($ids,'id,stock');
        }catch (\Exception $e){
            return false;
        }
        $goods = $goods->toArray();
        if(empty($goods)){
            return false;
        }

        //批量更新
        $updateList = [];
        foreach ($goods as $v){
            $updateList[] = [
                'id'    => $v['id'],
                'stock' => ($v['stock'] - $data[$v['id']])
            ];
        }

        try {
            $res = $this->model->saveAll($updateList);
        }catch (\Exception $e){
            return false;
        }

        return $res->toArray();
    }
}
